import numpy as np
import csv
from datetime import datetime
from time import strftime


def getCurTime():
    """
    get current time
    Return value of the date string format(%Y-%m-%d %H:%M:%S)
    """
    format='%Y-%m-%d %H:%M:%S'
    sdate = None
    cdate = datetime.now()
    try:
        sdate = cdate.strftime(format)
    except:
        raise ValueError
    return sdate

def build_data_list(inputCSV):
    sKey = []
    fn = inputCSV
    f = open(inputCSV)
    #ra = csv.DictReader(file(fn), dialect="excel")
    ra = csv.DictReader(f, dialect="excel")
    
    for record in ra:
        #print record[ra.fieldnames[0]], type(record[ra.fieldnames[-1]])
        for item in ra.fieldnames:
            temp = int(float(record[item]))
            sKey.append(temp)
    sKey = np.array(sKey)
    sKey.shape=(-1,len(ra.fieldnames))
    return sKey


#--------------------------------------------------------------------------
#MAIN

if __name__ == "__main__":
    print '===================================================='
    print "begin at " + getCurTime()

    filepath = 'C:/_DATA/migration_census_2000/'
    dataCSV = filepath + 'census_county_pop_state_fid.csv'
    data = build_data_list(dataCSV)
    #print data

    metroCountyCSV = filepath + 'metropolitan/metro_county_list.csv'
    metroCounty = build_data_list(metroCountyCSV)

    metro = np.unique(metroCounty[:,-1])
    metro_id = {}

    i = 0    
    for item in metro:
        metro_id[int(item)] = i
        i += 1

    county_id = {}

    for item in metroCounty:
        county_id[int(item[0])] = metro_id[int(item[1])]

    #print metro
    print metro_id

    
    for item in data:
        if int(item[1]) in county_id:
            item[-1] = county_id[int(item[1])]
        else:
            item[-1] = 999

    print max(data[:,-1])



    np.savetxt(filepath + 'metropolitan/census_county_pop_metro.csv', data, delimiter=',', fmt = '%s')
    